<template>
 <div class="container d-flex flex-column">
     <div class="m-b20">
         <label
                 class="m-r10"
         >部门</label>
         <el-select
                 v-model="state.responsibleDepartmentId"
                 clearable
                 @change="departmentChange"
         >
             <el-option
                     v-for="item in state.allDepartmentList"
                     :key="item.departmentId"
                     :label="item.departmentName"
                     :value="item.departmentId"
             />
         </el-select>
     </div>
     <div class="d-flex content-row">
         <div class="table-box m-r10">
             <common-title title-name="任务待发"/>
             <public-table
                     :header-cell-style="{'background':'#F5F5F5'}"
                     :page="page"
                     :height="'320'"
                     :is-paging="false"
                     border
                     :tableData="tableData"
                     :tableOption.sync="tableOption"
                     @pageChange="onPageChange"
             >
                 <template #buttons="scope">
                     <el-button size="small" type="primary" @click="getAllotUsers(scope.row)" class="button_edit">任务指派</el-button>
                 </template>
             </public-table>
         </div>

         <div class="table-box m-l10">
             <common-title title-name="人员统筹"/>
             <public-table
                     :header-cell-style="{'background':'#F5F5F5'}"
                     :page="page2"
                     :is-paging="false"
                     :height="'320'"
                     border
                     :tableData="userList"
                     :tableOption.sync="tableOption2"
             >
                 <template #buttons="scope">
                     <el-button size="small" type="primary" class="button_edit">任务指派</el-button>
                 </template>
             </public-table>
         </div>
     </div>
     <el-divider></el-divider>
     <div>
         <common-title :title-name="state.departmentName+'任务列表'"/>
         <public-table
                 :header-cell-style="{'background':'#F5F5F5'}"
                 :page="page3"
                 :height="'320'"
                 :tableData="taskList"
                 :tableOption.sync="tableOption3"
         >
             <template #interestStatus="scope">
                 <svg-icon
                         v-if="scope.row.interestStatus === 1"
                         icon-class="heart-active"
                 />
                 <svg-icon v-else icon-class="heart" />
             </template>
             <template #projectName="scope">
                 <span style="color: #ff7b56;cursor: pointer;" @click="toDetails(scope.row)">{{scope.row.projectName}}</span>
             </template>
             <template #buttons="scope">
                 <el-button size="small" type="primary" @click="toDetails(scope.row)" class="button_edit">详情</el-button>
             </template>
         </public-table>
     </div>
 </div>

    <public-dialog
        :title="'任务指派'"
        :width="'30%'"
        v-model:visible="state.visible"
        confirm-button-title="确认"
        @onConfirm="onConfirm"
    >
        <div class="public-dialog-content d-flex j-center a-center">
            <span class="m-r10">请选择任务的实施人员</span>
            <el-select v-model="state.allotUserId" filterable clearable>
                <el-option
                    v-for="(item, index) in state.allotUsers"
                    :key="index"
                    :value="item.userId"
                    :label="item.userName"
                ></el-option>
            </el-select>
        </div>
    </public-dialog>
</template>

<script setup>
import {ElDivider, ElSelect, ElOption, ElMessage} from "element-plus";
import CommonTitle from "@/components/CommonTitle.vue";
import PublicTable from "@/components/PublicTable.vue";
import {onMounted, reactive, ref} from "vue";
import {departmentTasks} from "@/api/taskImplementation";
import {department, userApi} from "@/api/project";
import PublicDialog from "@/components/PublicDialog.vue";
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import {localGet, localSet} from "@/common/utils/GlobalUtils";


const router = useRouter();
const store = useStore();

const page = reactive({
    total: 0,
    current: 1,
    size: 50
});
const tableData = ref([]);

const tableOption = ref([
    { label: '任务名称', prop: 'taskName' },
    { label: '所属项目', prop: 'projectName' },
    { label: '工期', prop: 'workPeriod' },
    {
        label: '操作',
        slot: true,
        width: 130,
        overHidden:false,
        slotName: 'buttons',
        fixed: "right"
    }
]);

const page2 = reactive({
    total: 0,
    current: 1,
    size: 5
});
const userList = ref([]);
const tableOption2 = ref([
    { label: '姓名', prop: 'userName' },
    { label: '岗位', prop: 'positionName' },
    { label: '部门', prop: 'deptName' },
    { label: '逾期', prop: 'exceedTaskNum' },
    { label: '未完成', prop: 'progressTaskNum' },
    { label: '已完成', prop: 'completedTaskNum' },
]);

const page3 = reactive({
    total: 0,
    current: 1,
    size: 50
});
const taskList = ref([]);
const tableOption3 = ref([
    { label: '重点关注', prop: 'interestStatus',slot:true },
    { label: '任务名称', prop: 'taskName' },
    { label: '所属项目', prop: 'projectName',slot: true },
    { label: '项目类型', prop: 'taskType' },
    { label: '计划开始时间', prop: 'planStartTime' },
    { label: '计划结束时间', prop: 'planEndTime' },
    { label: '计划工期', prop: 'workPeriod' },
    { label: '负责部门', prop: 'responsibleDepartmentName' },
    { label: '责任人', prop: 'responsibleUserName' },
    { label: '任务状态', prop: 'status',
        formatter: (val,row) => {
            let obj = {'-1':'未开始','-2':'待配置','0':'进行中','1':'完成'}
            if(row.exceedDays>0 && obj[val]){
                return obj[val]+'(已逾期)';
            }
            return obj[val] || '-';
        },
    },
    { label: '逾期天数', prop: 'exceedDays' },
    {
        label: '操作',
        slot: true,
        width: 130,
        overHidden:false,
        slotName: 'buttons',
        fixed: "right"
    }
]);

/**
 * 任务分页列表
 */
const getPendingTasks = (params) => {
    departmentTasks.getPendingTasks(params).then(res=>{
        if(res.code==='200'){
            taskList.value = res.data.content;
            page3.total = res.data.totalSize;

        }
    });
}

/**
 * 任务待发分页
 * @param e
 */
const onPageChange = (e) => {
    page.current = e.page;
    page.size = e.limit;
    let params = {
        param: {
            // status:-2
        },
        pageNum: page.current,
        pageSize: page.size,
    };
    getPendingTasks(params);
}

/**
 * 人员统筹
 */
const getPersonnelCoordination = (params) => {
    departmentTasks.getPersonnelCoordination(params).then(res=>{
      if(res.code === '200'){
          userList.value = res.data;
      }
    });
}

/**
 * 待分配任务列表
 */
const getTaskList = (params) => {
    departmentTasks.getTaskList(params).then(res=>{
        if(res.code==='200'){
            tableData.value = res.data;
        }
    });
}

const state = reactive({
    allotUserId:'',
    projectTaskId:'',
    departmentId:'',
    allotUsers:[],
    departmentName:'',
    responsibleDepartmentId:'',
    allDepartmentList:[]
});

/**
 * 获取所有部门
 */
const getAllDepartments = () => {
    department.getAllDepartments().then((res) => {
        const { code, data } = res;
        if (code === '200') {
            // state.allDepartmentList = data;
            state.allDepartmentList = data.filter(item=>{
                if(item.departmentId === store.state.user.departmentId){
                    return item;
                }
            });
        }
    });
};

/**
 * 根据部门id查询用户
 * @param row
 */
const getAllotUsers = (row) => {
    state.projectTaskId = row.projectTaskId;
    state.allotUserId = '';
 /*   userApi.getAlluserList('').then(res=>{
        if (res.code === '200') {
            state.allotUsers = res.data
            state.visible = true
        }
    });*/
    department.getUserByDepartmentId(localGet('DepartmentId')).then(res=>{
        if (res.code === '200') {
            state.allotUsers = res.data
            state.visible = true
        }
    });
}

/**
 * 确认
 */
const onConfirm = () => {
    if (state.allotUserId.trim() === '') {
        return ElMessage.warning('请选择实施人员!')
    }
    departmentTasks.taskAllocation({projectTaskId:state.projectTaskId,userId:state.allotUserId})
        .then(res=>{
            if(res.code==='200'){
                ElMessage.success('指派成功!');
                state.visible = false;

                page.current = 1;
                page.size = 50;
                getPendingTasks({
                    pageNum:1,
                    pageSize:50,
                    param:{
                        // status:-2
                    }
                });
                getPersonnelCoordination();
                getTaskList();
            }else{
                ElMessage.error('指派失败!');
                state.visible = false;
            }
        });
}

/**
 * 根据部门id查询
 * @param e
 */
const departmentChange = (e) => {
    state.departmentId = e;
    let i = state.allDepartmentList.findIndex(x=>x.departmentId===e);
    if(i!==-1){
        state.departmentName = state.allDepartmentList[i].departmentName;
    }
    if(!e){
        state.departmentName = '';
    }
    getPendingTasks({
        pageNum:page.current,
        pageSize:page.size,
        param:{
            // status:-2,
            departmentId:e,
        }
    });
    getPersonnelCoordination({ departmentId:e});
    getTaskList({ departmentId:e});

}

/**
 * 跳转详情
 */
const toDetails = (row) => {
   /* router.push({
        path: `/constructionProjectManage/projectsPectaculars/pectaculars/type=${1}&id=${
            row?.projectId || ''
        }&name=${row?.projectName || ''}&projectType=${row?.type}&tabId=${row?.type}`
    })*/
    router.push({path:`/taskImplementationManagement/projectTaskImplementation/taskDetails/projectTaskId=${row.projectTaskId}`})
}

onMounted(()=>{
    getPendingTasks({
        pageNum:1,
        pageSize:50,
        param:{
            // status:-2
        }
    });
    getPersonnelCoordination();
    getTaskList();
    getAllDepartments();
});
</script>

<style lang="scss" scoped>
  .container{
    width: 100%;
    .content-row{
      width: 100%;

      .table-box{
        width: 50%;
      }
    }
  }
</style>
